#!/bin/bash


:<<EOF
    封装这个功能作为一个函数,  来 加载 CSV 文件到 mysql中
EOF




# 构造函数
# @param  @notNull  csvpath              数据文件路径
# @param  @notNull  table                导入表
# @param  @notNull  columns              导入列
# @param  @notNull  import_date          导入日期
# @param  @notNull  env                  环境参数
function  LOAD_CSV_FUNCTION(){


    local  csvpath=$1
    local  table=$2
    local  columns=$3
    local  import_date=$4
    local  env=$5

    LOAD_CSV_FUNCTION_RESP='' ;  #  return  result ;

    local script_path=$(dirname "$0")                           # 当前脚本路径
    BUILD_COMMAND_SQL=$script_path"/""BUILD_COMMAND_SQL.sh"
    source  "$BUILD_COMMAND_SQL"
    LOG4S=$script_path"/""LOG4S.sh"
    source  "$LOG4S"



    BUILD_COMMAND_SQL  "'${csvpath}'"  ${table}   ${columns}   "sync_date='${import_date}'"

    local config_file_path=$(dirname "$script_path")/config
    local log_file_path=$(dirname "$script_path")/var/dataMarket/${env}/${import_date}/${table}.log
    if [ -w $log_file_path ]; then
        echo  "log_file_path ==>  ${log_file_path}"
    else
        mkdir  -p   $(dirname "$script_path")/var/dataMarket/${env}/${import_date}
        touch  ${log_file_path}
    fi


    if [[   ${env} = "prod" ]]; then
        config_file=$config_file_path/mysql_client_prod.conf
    elif [[  ${env} = "dev"   ]]; then
        config_file=$config_file_path/mysql_client_dev.conf
    else
        config_file=$config_file_path/mysql_client_local_dev.conf
    fi


    #记录导入那天有多少条重复
    count_sql="select count(*)  as  before_import_count  from   ${table}  where sync_date between '${import_date} 00:00:00' AND '${import_date} 23:59:59'   "
    LOG4S_info  "count_sql ==> ${count_sql}"       $log_file_path
    local  data_res=$(mysql --defaults-file=$config_file -e "$count_sql")
    # echo  " data_res ==>   ${data_res}"
    local  data_num=${data_res/before_import_count/""}                       #字符串替换 顶掉  resultSet 的 columnName
    data_num=$(echo $data_num | xargs)                                       #trim 掉 数字旁边的空字符
    LOG4S_info "${import_date} 重复的数据量是  ${data_num} "      $log_file_path
    if [[ "${data_num}" ==  "0"   ]]; then

        LOG4S_debug "准本导入${table}"        $log_file_path
    else
        #预处理 ， 防止重复， 先删掉 当天导入的；
        delete_sql="delete from    ${table}   where sync_date between '${import_date} 00:00:00' AND '${import_date} 23:59:59'   "
        LOG4S_warn  "delete_sql ==> ${delete_sql}"       $log_file_path
        mysql --defaults-file=$config_file -e "$delete_sql"
    fi


    LOG4S_info  "执行sql ==>  ${FINAL_SQL}"       $log_file_path
    $(mysql --defaults-file="$config_file" -e "$FINAL_SQL")
    if [ $? -ne 0 ]; then
        LOAD_CSV_FUNCTION_RESP="写入 ${table} 失败"
        LOG4S_error  "$LOAD_CSV_FUNCTION_RESP ,  sql execute failed"         $log_file_path
    else
        LOAD_CSV_FUNCTION_RESP="写入 ${table} 成功"
        LOG4S_warn   "$LOAD_CSV_FUNCTION_RESP ,  sql execute succeed"        $log_file_path
    fi

}









